<?php

class UploadController extends Zend_Controller_Action {
	
	public function reportAction() {
		
		$user_email = $this->_getParam("user_email");
		$message = $this->_getParam("message");
		$latitude = $this->_getParam("latitude");
		$longitude = $this->_getParam("longitude");
		$species = $this->_getParam("species");
		$report_datetime = $this->_getParam("report_datetime");
		
		$application_model_user = new Application_Model_User();
		
		if ($user_email === null || !$application_model_user->isUserEmail($user_email)) {
			$output = <<<XML
<output>
	<result>
		false
	</result>
	<error>
		<code>
			0
		</code>
		<message>
			Email not valid.
		</message>
	</error>
</output>
XML;
		} else { 
			if ($latitude === null || $longitude === null) {
				$output = <<<XML
<output>
	<result>
		false
	</result>
	<error>
		<code>
			1
		</code>
		<message>
			Coordinates not given.
		</message>
	</error>
</output>
XML;
			} else { 
				$latitude = doubleval($latitude);
				$longitude = doubleval($longitude);
				if ($message !== null) {
					$message = trim($message);
					if (strlen($message) == 0) {
						$message = null;
					}
				}
				if ($species !== null) {
					$species = trim($species);
					if (strlen($species) == 0) {
						$species = null;
					}
				}
				try {
					$photo = PhpThumbFactory::create($_FILES["photo"]["tmp_name"]);
				} catch (Exception $e) {
					$photo = null;
				}
				if ($species === null && $photo === null) {
					$output = <<<XML
<output>
	<result>
		false
	</result>
	<error>
		<code>
			2
		</code>
		<message>
			Species or photo must be given.
		</message>
	</error>
</output>
XML;
				} else {
					try {
						$report_datetime = new Zend_Date($report_datetime, DATETIME_FORMAT);
					} catch (Exception $e) {
						$report_datetime = null;
					}
					if ($report_datetime === null) {
						$output = <<<XML
<output>
	<result>
		false
	</result>
	<error>
		<code>
			3
		</code>
		<message>
			Invalid report datetime given.
		</message>
	</error>
</output>
XML;
					} else {
						if ($species !== null) {
							$species = trim($species);
						}
						$application_model_report = new Application_Model_Report();
						$report_datetime = $report_datetime->toString(DATETIME_FORMAT);
						if (!$application_model_report->insertReport(
							$user_email, 
							$report_datetime,
							$message, 
							$species, 
							$latitude, 
							$longitude)) {
							throw new Zend_Controller_Action_Exception("Internal server error", 500);
						} else {
							if ($photo !== null) {
								$filename = APPLICATION_PATH . "/photos/" . $user_email . " - " . $report_datetime;
								$photo->save($filename, "JPG");
							}
							$output = <<<XML
<output>
	<result>
		true
	</result>
</output>
XML;
						}
					}
				}
			}
		}
		
		exit($output);
		
	}
	
}